

import React,{Component} from 'react';
import PropTypes from 'prop-types';
import {Route,NavLink,Redirect} from 'react-router-dom';

import {ChoiceQuestion,Option,ChoiceQuestionList} from '../common/ChoiceQuestionModel';


import './AnswerQuestions.less';


class AnswerQuestions extends Component {

    state = {
        wastedTime: new Date(0,0,0,0,0,0,0),
        questions:null,
        questionIdex:0
    };

    static propTypes = {
        history: PropTypes.object.isRequired
      };

    static contextTypes = {
        setNavConfig: PropTypes.func
    };


    constructor(props,context){
        super(props,context);
        
        this.recordTime = this.recordTime.bind(this);
        this.nextQuestion = this.nextQuestion.bind(this);

        this.getQuestionList();


        context.setNavConfig(this.navConfig);
        
        
    }

    get navConfig(){
        return {
            center:"布拉题库"
        };
    }

    componentDidMount(){
        this.intervalID = setInterval(this.recordTime,1000);
        
    }

    componentWillUnmount(){
        if (this.intervalID){
            clearInterval(this.intervalID);
        }
        
    }


    get wastedTime(){
        let wastedTime = this.state.wastedTime;

        let timeStr = wastedTime.toTimeString();
        timeStr = timeStr.substr(0,8);

        return timeStr;
    }

    recordTime(){
        let wastedTime = this.state.wastedTime;
        let milliseconds = wastedTime.getTime();
        milliseconds += 1000;
        wastedTime.setTime(milliseconds);
        this.setState({wastedTime: wastedTime});
    }



    getQuestionList(){
        window.$.get("http://result.eolinker.com/PMR6Shb6b68e3043d93f7ca7ddf92fd26b5024ee06fdfb7?uri=https://api.blatrip.com/v2/island-answer/init",null,(data,textStatus)=>{
            
        if (data.error_code == 0){
            let questions = this.parseQuestionDate(data.data);
            this.setState({questions:questions});
        }
        
        },"json");
    }

    submitAnswer(){
        clearInterval(this.intervalID);
        this.intervalID = null;
        let answers = this.pickupAnswer();

        window.$.post("http://result.eolinker.com/PMR6Shb6b68e3043d93f7ca7ddf92fd26b5024ee06fdfb7?uri=https://api.blatrip.com/v2/island-answer/submit",answers,(data,textStatus)=>{
            
        if (data.error_code == 0){
            this.props.history.push({pathname: '/score'});
        }
        
        },"json");
    }

    pickupAnswer(){
        let questions = this.state.questions;

         let answers = questions.questionList.map(function(quest,index){
             let wastedTime = quest.wastedTime;

             let wastedTimeStr = `${wastedTime.getHours()}时${wastedTime.getMinutes()}分${wastedTime.getSeconds()}秒`;

            return {
                topic_id:quest.id,
                answer:quest.selectedIds[0],
                spend_time:wastedTimeStr
            };
        });

        return answers;
    }


    parseQuestionDate(questionData){
        let questionList = questionData.map(function(question,index){

            let choiceQuestion = new ChoiceQuestion(question.title,1,1);
            Object.assign(choiceQuestion,question);
            choiceQuestion.originalData = question;

            let optionList = question.answer.map(function(answer,index){
                let optionId = Object.keys(answer)[0];
                let option = new Option(answer[optionId],optionId,choiceQuestion);
                return option;
            });

            choiceQuestion.options = optionList;
            return choiceQuestion;

        });

        return new ChoiceQuestionList(questionList);
    }


    optionSelectedhandle(index,event){
        if (this.timeoutID){
            clearTimeout();
        }
        

        let {questions,questionIdex} = this.state;
        let curQue =  questions.questionList[questionIdex];
        curQue.deselect();
        curQue.options[index].selected = true;
        curQue.wastedTime = this.state.wastedTime;

        this.setState({questions:questions});
        
        setTimeout(this.nextQuestion,1000);

    }

    nextQuestion(){
        this.timeoutID = null;

        let {questions,questionIdex} = this.state;
        questionIdex = questionIdex + 1;
        let questionCount = questions.questionList.length;

        if (questionIdex + 1 <= questionCount){
            let wastedTime = new Date(0,0,0,0,0,0,0);
            this.setState({wastedTime,questionIdex});
        }else {
            this.submitAnswer();
        }

        
    
    }
    

    render(){

        let {questions,questionIdex} = this.state;

        let curQue =  null;
        let questionCount = null;
        let optionList = null;
        let questType = "";
        if (questions){
            curQue =  questions.questionList[questionIdex];
            questionCount = questions.questionList.length;
            questType = curQue.type;

            optionList = curQue.options.map((option,index)=>{
                return <li className={`option ${(option.selected ? "selected" : "")}`} onClick={this.optionSelectedhandle.bind(this,index)} key={index} >{option.content}</li>;
            });
        }
        

        return (
            <div className={`answer-questions ${ questType }`}>
                <div className="answer-img"></div>
                <div className="question-area">
                    <p className="index-area">
                        <span className="index">{questions && `${questionIdex + 1}/${questionCount}`}</span>
                        <span className="time-record">{questions &&  this.wastedTime}</span>
                    </p>
                    <p className="question" >{questions && curQue.subject}</p>

                    <ul className="option-area" >{optionList}</ul>

                </div>
                
            </div>
        );
    }
}





export default AnswerQuestions;